package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"groupchat/basic/config"
	"groupchat/handler/model"
	"groupchat/handler/request"
	"math/rand"
	"net/http"
	"strconv"
)

func Register(c *gin.Context) {
	var form request.Register
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var user model.User
	if err := user.IsPhone(config.DB, form.Phone); err == nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "手机号已注册,请登录",
		})
		return
	}
	smsCode, _ := config.Rdb.Get(config.Ctx, "smsCode_"+form.Phone).Result()
	if smsCode != form.SmsCode {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "验证码错误",
		})
		return
	}
	user = model.User{
		Phone:    form.Phone,
		QQ:       strconv.Itoa(rand.Intn(100000000000)),
		NickName: fmt.Sprintf("游客_%d", rand.Intn(10000)),
		Password: form.Password,
	}
	if err := user.Register(config.DB); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "注册失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
	return
}

func LoginByQQ(c *gin.Context) {
	var form request.LoginByQQ
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var user model.User
	if err := user.IsQQ(config.DB, form.QQ); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "QQ号未注册",
		})
		return
	}
	if user.Password != form.Password {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func LoginByPhone(c *gin.Context) {
	var form request.LoginByPhone
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var user model.User
	if err := user.IsPhone(config.DB, form.Phone); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "手机号未注册",
		})
		return
	}
	if user.Password != form.Password {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func SearchUser(c *gin.Context) {
	var form request.SearchUser
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var user model.User
	if err := user.SearchUser(config.DB, form.Keyword); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"user": user,
		},
	})
	return
}
